package com.lyandwc.lw_bbs.security.common;

import com.lyandwc.lw_bbs.security.entity.UserAuthDetails;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class UserAuthProvider implements AuthenticationProvider {

    private UserAuthDetailsService userAuthDetailsService;

    public UserAuthProvider(UserAuthDetailsService userAuthDetailsService) {
        this.userAuthDetailsService = userAuthDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        UserAuthDetails userAuthDetails = (UserAuthDetails) userAuthDetailsService.loadUserByUsername(username);

        if (userAuthDetails == null) {
            throw new UsernameNotFoundException("不存在名为'" + username + "'的用户");
        }
        if (!new BCryptPasswordEncoder().matches(password, userAuthDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        if (userAuthDetails.getStatus() == 2) {
            throw new LockedException("用户已禁用");
        }

        return new UsernamePasswordAuthenticationToken(
                userAuthDetails,
                userAuthDetails.getId(),
                userAuthDetails.getAuthorities()
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
